#include "SCAN.h"
#include <vector>
#include <list>
#include "Position.h"
#include "Requisition.h"
#include <iostream>

using namespace std;

SCAN::SCAN(int nT, Disk * d) : numTracks(nT), disk(d)
{
	goingUP=true;
	curTrack=0;
	
	for (int i = 0; i < nT; i++) {
		queue<Requisition> * dummyList = new queue<Requisition>;
		diskList.push_back(dummyList);
	}

}

SCAN::~SCAN()
{
}

void SCAN::enqueue(Requisition pos)
{
	diskList[pos.track]->push(pos);
}

Requisition SCAN::next(Position p)
{
//	cout << "Parti de " << p.track << ", " << p.sector << endl;
	Requisition pos;
	curTrack = p.track;
	if(diskList[curTrack]->size()!=0)
	{
		pos = diskList[curTrack]->front();
		diskList[curTrack]->pop();
//		cout << "***Retornando aposicao " << pos.track << ", " << pos.sector << endl;
		return pos;
	}
	else
	{
//		int beginTrack=curTrack;
		int breakTrack;
		goingUP ? breakTrack = 0 : breakTrack = numTracks;
		do
		{
//			cout << "comeco loop, track: " << curTrack << endl;
			if(goingUP)
			{
				curTrack++;
				if(curTrack >= numTracks)
				{
					disk->setChanged(true);
//						cout << "Parti de " << p.track << ", " << p.sector << endl;
					cout << "Agora descendo..." << endl;
					goingUP = false;
					curTrack = numTracks-1;
				}
			}
			else
			{
				curTrack--;
				if(curTrack < 0)
				{
					disk->setChanged(true);
//						cout << "Parti de " << p.track << ", " << p.sector << endl;
					cout << "Agora subindo..." << endl;
					goingUP = true;
					curTrack = 0;
				}
			}
			if(diskList[curTrack]->size()!=0)
			{
				pos = diskList[curTrack]->front();
				diskList[curTrack]->pop();
//				cout << "***Retornando posicao " << pos.track << ", " << pos.sector << endl;
				return pos;
			}
		}while(curTrack != breakTrack);
		Requisition p;
		p.sector=-1;
		p.track=-1;
//		cout << "***Retornando pposicao " << p.track << ", " << p.sector << endl;
		return p;
	}
}